package com.hmdp.service.impl;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.hmdp.dto.Result;
import com.hmdp.entity.ShopType;
import com.hmdp.mapper.ShopTypeMapper;
import com.hmdp.service.IShopTypeService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

import java.util.List;
import java.util.concurrent.TimeUnit;

import static com.hmdp.utils.RedisConstants.CACHE_SHOP_TYPE_KEY;
import static com.hmdp.utils.RedisConstants.CACHE_SHOP_TYPE_TTL;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Slf4j
@Service
public class ShopTypeServiceImpl extends ServiceImpl<ShopTypeMapper, ShopType> implements IShopTypeService {

    @Resource
    private StringRedisTemplate stringRedisTemplate;
    @Override
    public Result queryShopList() {
        // 查询Redis 当中是否缓存有商户列表数据
        String shopForTypeListStr = stringRedisTemplate.opsForValue().get(CACHE_SHOP_TYPE_KEY);
        if (!StrUtil.isBlank(shopForTypeListStr)){
            // 缓存中有商户列数据 直接返回  // 这里需要先将这里的每个Shop小类转换成Shop对象
//            List<ShopType> shopForTypeList= JSONUtil.toList(JSONUtil.parseArray(shopForTypeListStr), ShopType.class);
            List<ShopType> shopForTypeList= JSONUtil.toList(shopForTypeListStr, ShopType.class);
            log.info("取出数据：{}",shopForTypeList);
            return Result.ok(shopForTypeList);
        }
        // 如果没有数据 查询数据库
        List<ShopType> typeList = query().orderByAsc("sort").list();
        if (typeList.isEmpty()){
            return Result.fail("商户列表数据不存在");
        }
        // 存入Redis 缓存
        stringRedisTemplate.opsForValue().set(CACHE_SHOP_TYPE_KEY,JSONUtil.toJsonStr(typeList),CACHE_SHOP_TYPE_TTL, TimeUnit.MINUTES);

        return Result.ok(typeList);
    }
}
